<?php
    header("content-type:text/html;charset=utf-8;");
    $usr = @$_POST["username"];
    $pwd = @$_POST["password"];
    $tocken = @$_COOKIE["TOCKEN"];

    //账号密码为空 存在cookie
    if($tocken && !$pwd && !$usr){
        die($tocken);
    }
    //连接数据库
    $host = "localhost:3306";
    $username = "root";
    $password = "123";
    $dbname   = "daweige";

    $conn = mysqli_connect($host,$username,$password,$dbname);
    
    if(!$conn){
        //服务器延时
        $result = array("state" => "error" , "stateCode" => 0 ,"errorMsg" => mysqli_error($conn));
        die(json_encode($result));
    }

    $sql_select = "SELECT username,password FROM admin where username = '$usr'";

    $sql_insert = "INSERT INTO admin (username,password) VALUES ('$usr' ,'$pwd')";

    $res = mysqli_query($conn,$sql_select);

    if(mysqli_num_rows($res) === 0){
        //用户名不存在
        $result = array( "state" => "error", "stateCode" => 2);
        die( json_encode($result));
    }else{
        while($row = mysqli_fetch_assoc($res)){
            if($row["password"] == $pwd){
                //登录成功
                $result = array( "state" => "success" , "stateCode" => 1 , "username" => $usr , "password" => $row["password"]);
                $tocken = array( "username" => $usr,"password" => $row["password"]);
                
                setcookie("TOCKEN", json_encode($tocken),time()+3600*24 );
                die(json_encode($result));
            }
        }
        //密码错误
        $result = array( "state" => "error" , "stateCode" => 3 );
        die( json_encode($result) );
    }
?>